package com.example.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.R;
import com.example.common.utils.SnowFlake;
import com.example.system.entity.MedicalCertificate;
import com.example.system.entity.Order;
import com.example.system.mapper.AppointmentSchedulerMapper;
import com.example.system.mapper.MedicalCertificateMapper;
import com.example.system.mapper.OrderMapper;
import com.example.system.service.IMedicalCertificateService;
import com.example.system.service.IUserService;
import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王鹤蒲
 * @since 2024-03-02
 */
@Service
public class MedicalCertificateServiceImpl extends ServiceImpl<MedicalCertificateMapper, MedicalCertificate> implements IMedicalCertificateService {

    @Autowired
    private SnowFlake snowFlake;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MedicalCertificateMapper medicalCertificateMapper;


    @Autowired
    private IUserService iUserService;

    @Override
    public R createMedicalCertificate(String orderNo, MedicalCertificate medicalCertificate) {
        String certificateNo = "mc" + snowFlake.nextId();
        medicalCertificate.setCertificateNo(certificateNo).setCreateBy(iUserService.getCurrentLoginUser().getUserName()).setCreateTime(LocalDateTime.now());
        medicalCertificateMapper.insert(medicalCertificate);
        LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        orderLambdaUpdateWrapper.eq(Order::getOrderNo, orderNo);
        orderLambdaUpdateWrapper.set(Order::getCertificateNo, certificateNo);
        orderLambdaUpdateWrapper.set(Order::getUpdateBy, iUserService.getCurrentLoginUser().getUserName());
        orderLambdaUpdateWrapper.set(Order::getUpdateTime, LocalDateTime.now());
        orderMapper.update(new Order(), orderLambdaUpdateWrapper);
        return R.success();
    }

    @Override
    public void downloadMedicalCertificate(String certificateNo, HttpServletResponse response)  {
        Order order = orderMapper.selectOrderMedicalCertificateDetailInfo(certificateNo);
        System.out.println(order);
        String patientName=order.getPatient().getUser().getUserName();
        String patientSex=null;
        if("0".equals(order.getPatient().getUser().getSex())){
           patientSex="男";
        }else{
           patientSex="女";
        }
        String patientBirthDate=order.getPatient().getBirthDate().toString();
        String patientIdNumber=order.getPatient().getIdNumber();
        String patientAddress=order.getPatient().getUser().getAddress();
        String doctorName=order.getAppointmentScheduler().getDoctor().getUser().getUserName();
        String departmentName=order.getAppointmentScheduler().getDoctor().getDepartment().getName();
        String selfReport=order.getMedicalCertificate().getSelfReport();
        String diagnosticOpinion=order.getMedicalCertificate().getDiagnosticOpinion();
        String medicalAdvice=order.getMedicalCertificate().getMedicalAdvice();
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String issueTime=order.getMedicalCertificate().getCreateTime().format(formatter);
        String printTime=LocalDateTime.now().format(formatter);
        Document document=new Document(new RectangleReadOnly(842F, 595F));
        try {
            StringBuilder fileName=new StringBuilder();
            fileName.append("医学诊断报告（").append(patientName).append("）_").append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())).append(".pdf");
            ByteOutputStream byteOutputStream=new ByteOutputStream();
            PdfWriter.getInstance(document,byteOutputStream);
            document.open();
            BaseFont bfChinese = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, BaseFont.NOT_EMBEDDED);
            Font fontChina18 = new Font(bfChinese, 18,Font.BOLD);
            Font fontChina12 = new Font(bfChinese, 12);
            Font boldFontChina12 = new Font(bfChinese, 12,Font.ITALIC);
            Paragraph titleParagraph1=new Paragraph("东华市新桥社区医院",fontChina18);
            Paragraph titleParagraph2=new Paragraph("医学诊断报告",fontChina18);
            titleParagraph1.setAlignment(Element.ALIGN_CENTER);
            titleParagraph2.setAlignment(Element.ALIGN_CENTER);
            document.add(titleParagraph1);
            document.add(titleParagraph2);
            Paragraph blankParagraph=new Paragraph(" ");
            document.add(blankParagraph);
            PdfPTable table=new PdfPTable(8);
            table.setWidthPercentage(100);
            float[] columnWidths = {0.125f, 0.125f,0.125f, 0.07f, 0.125f, 0.125f,0.125f, 0.18f};
            table.setWidths(columnWidths);
            PdfPCell cell=new PdfPCell();
            cell.setColspan(7);
            cell.setVerticalAlignment(PdfPCell.ALIGN_BOTTOM);
            cell.setBorder(0);
            cell.setPhrase(new Paragraph("No："+certificateNo,boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setColspan(6);
            cell.setVerticalAlignment(PdfPCell.ALIGN_BOTTOM);
            cell.setBorder(0);
            cell.setPhrase(new Paragraph(issueTime,boldFontChina12));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setFixedHeight(40);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("姓名",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(patientName,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("性别",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(patientSex,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("出生日期",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(patientBirthDate,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("身份证号码",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(patientIdNumber,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setFixedHeight(40);
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("家庭地址",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setColspan(5);
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(patientAddress,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("就诊科室",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(departmentName,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setFixedHeight(80);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("主诉与症状",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setColspan(7);
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(selfReport,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setFixedHeight(80);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("诊断意见",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setColspan(7);
            cell.setBorderWidth(0.5F);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph(diagnosticOpinion,fontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setBorderWidth(0.5F);
            cell.setFixedHeight(80);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setPhrase(new Paragraph("医嘱意见",boldFontChina12));
            table.addCell(cell);
            cell=new PdfPCell();
            cell.setColspan(7);
            cell.setBorderWidth(0.5F);
            Paragraph paragraph1=new Paragraph(medicalAdvice,fontChina12);
            Paragraph signatureParagraph1=new Paragraph("医生签名："+doctorName,boldFontChina12);
            signatureParagraph1.setAlignment(Element.ALIGN_RIGHT);
            signatureParagraph1.setIndentationRight(40);
            signatureParagraph1.setExtraParagraphSpace(60);
            cell.addElement(paragraph1);
            cell.addElement(blankParagraph);
            cell.addElement(blankParagraph);
            cell.addElement(blankParagraph);
            cell.addElement(signatureParagraph1);
            table.addCell(cell);
            document.add(table);
            Paragraph printParagraph=new Paragraph("打印日期："+printTime,fontChina12);
            printParagraph.setAlignment(Element.ALIGN_LEFT);
            document.add(printParagraph);
            document.close();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName.toString(), "UTF-8"));
            response.addHeader("Access-Control-Expose-Headers", "Content-disposition");
            response.setContentType("application/octet-stream");
            OutputStream outputStream =response.getOutputStream();
            byteOutputStream.writeTo(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
